<template>
	<view class="content">
		<view>
			<button type="primary" @tap="choose_image">选择图片</button>
		</view>
		<view>
			<image style="width: 200px; height: 200px; background-color: #eeeeee;" mode="aspectFill" :src="src" @tap="preview_image"></image>
		</view>
		<view>
			<button type="primary" @tap="upload_image">上传图片</button>
		</view>
	</view>
</template>

<script>
	import config from '../../lib/config.js';
	export default {
		data() {
			return {
				tempFilePaths: null,
				src: null,
			}
		},
		methods: {
			choose_image: function() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						this.tempFilePaths = res.tempFilePaths;
					}
				});
			},
			upload_image: function() {
				if (!this.tempFilePaths) {
					uni.showToast({
						title: '请选择图片',
						duration: 2000,
						icon: 'none',
					});
					return;
				}
				uni.uploadFile({
					url: config.api_url + '?action=upload_image', //仅为示例，非真实的接口地址
					filePath: this.tempFilePaths[0],
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes.data);
						let json = JSON.parse(uploadFileRes.data);
						uni.showToast({
							title: json.msg,
							duration: 2000,
							icon: 'none',
						});
						let src = json.data.url;
						this.src = src;
					}
				});
			},
			preview_image: function() {
				if(!this.src){
					return false;
				}
				uni.previewImage({
					urls: [this.src],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			}
		}
	}
</script>

<style>

</style>
